#include "chatuserwid.h"
#include "chatwidget.h"
#include "loadingdlg.h"
#include "ui_chatwidget.h"
#include<QRandomGenerator>
#include <QAction>
#include <QTimer>
#include <QPixmap>
#include "global.h"
#include "tcpmgr.h"


ChatWidget::ChatWidget(QWidget *parent) :
    QWidget(parent),_mode(ChatUIMode::ChatMode),
    _state(ChatUIMode::ChatMode),_bLoading(false),_windowFlag(false),
    ui(new Ui::ChatWidget)
{
    ui->setupUi(this);
    setTitleBar();
    setStateBar();
    setSearchBar();
    ui->add_btn->SetState("normal","hover","press");
    //  限制搜索的最大长度
    ui->searchEdit->setMaxLength(15);
    // 创建搜索的图标
    QAction *searchAction = new QAction(ui->searchEdit);
    searchAction->setIcon(QIcon(":/Img/search.png"));
    ui->searchEdit->addAction(searchAction,QLineEdit::LeadingPosition);
    // 设置默认的文本
    ui->searchEdit->setPlaceholderText(QStringLiteral("搜索"));
    //为searchlist 设置search edit
    ui->searchList->SetSearchEdit(ui->searchEdit);

    // 创建一个清除动作并设置图标
    QAction *clearAction = new QAction(ui->searchEdit);
    // 初始时不显示清除图标
    // 将清除动作添加到LineEdit的末尾位置
    ui->searchEdit->addAction(clearAction, QLineEdit::TrailingPosition);
    // 当需要显示清除图标时，更改为实际的清除图标
    connect(ui->searchEdit, &QLineEdit::textChanged, [clearAction](const QString &text) {
        if (!text.isEmpty()) {
            clearAction->setIcon(QIcon(":/Img/close_search.png"));
        } else {
            clearAction->setIcon(QIcon(":/Img/close_transparent.png")); // 文本为空时，切换回透明图标
        }
    });
    // 连接清除动作的触发信号到槽函数，用于清除文本
    connect(clearAction, &QAction::triggered, [this, clearAction]() {
        ui->searchEdit->clear();
        ui->searchEdit->clearFocus();
        ShowSearch(false);
    });
    ShowSearch(false);

    connect(ui->chatUserList,&ChatUserList::SigLoadingChatUser,this,
            &ChatWidget::SlotLoadingChatUser);

    //连接申请添加好友信号
    connect(TcpMgr::GetInstance().get(), &TcpMgr::SigFriendApply, this, &ChatWidget::SlotApplyFriend);

    //连接对端消息通知
    connect(TcpMgr::GetInstance().get(), &TcpMgr::SigTextChatMsg,
            this, &ChatWidget::SlotTextChatMsg);

    this->installEventFilter(this); // 安装事件过滤器

}



void ChatWidget::ShowSearch(bool bsearch)
{
    if(bsearch){
           qDebug() << "切换到搜索好友";
        ui->chatUserList->hide();
        ui->conUserList->hide();
        ui->searchList->show();
        _mode = ChatUIMode::SearchMode;
    }else if(_state == ChatUIMode::ChatMode){
          qDebug() << "切换到聊天好友";
        ui->chatUserList->show();
        ui->conUserList->hide();
        ui->searchList->hide();
        _mode = ChatUIMode::ChatMode;
    }else if(_state == ChatUIMode::ContactMode){
        qDebug() << "切换到添加好友";
        ui->chatUserList->hide();
        ui->searchList->hide();
        ui->conUserList->show();
        _mode = ChatUIMode::ContactMode;
    }
}
ChatWidget::~ChatWidget()
{
    delete ui;
}






void ChatWidget::SlotLoadingChatUser()
{
    if(_bLoading){
           return;
       }

       _bLoading = true;
       LoadingDlg *loadingDialog = new LoadingDlg(this);
       loadingDialog->setModal(true);
       loadingDialog->show();
       qDebug() << "add new data to list.....";
       // 加载完成后关闭对话框
       loadingDialog->deleteLater();
       _bLoading = false;
}

void ChatWidget::setStateBar()
{
    QPixmap pixmap(":/avatar/head_1.jpg");
    ui->side_head_lb->setPixmap(pixmap); // 将图片设置到QLabel上
    QPixmap scaledPixmap = pixmap.scaled( ui->side_head_lb->size(), Qt::KeepAspectRatio); // 将图片缩放到label的大小
    ui->side_head_lb->setPixmap(scaledPixmap); // 将缩放后的图片设置到QLabel上
    ui->side_head_lb->setScaledContents(true); // 设置QLabel自动缩放图片内容以适应大小

    ui->side_chat_lb->setProperty("state","normal");

    ui->side_chat_lb->SetState("normal","hover","pressed","selected_normal","selected_hover","selected_pressed");

    ui->side_contact_lb->SetState("normal","hover","pressed","selected_normal","selected_hover","selected_pressed");

    AddLBGroup(ui->side_chat_lb);
    AddLBGroup(ui->side_contact_lb);

    connect(ui->side_chat_lb, &StateWidget::clicked, this, &ChatWidget::slot_side_chat);
    connect(ui->side_contact_lb, &StateWidget::clicked, this, &ChatWidget::slot_side_contact);

    ui->side_chat_lb->SetSelected(true);
}

void ChatWidget::slot_side_chat()
{
    qDebug()<< "receive side chat clicked";
    ClearLabelState(ui->side_chat_lb);
    ui->stackedWidget->setCurrentWidget(ui->chatPage);
    _state = ChatUIMode::ChatMode;
    ShowSearch(false);
}

void ChatWidget::slot_side_contact()
{
    qDebug()<< "receive side contact clicked";
    ClearLabelState(ui->side_contact_lb);
    ui->stackedWidget->setCurrentWidget(ui->friendApplyPage);
    _state = ChatUIMode::ContactMode;
    ShowSearch(false);
}

void ChatWidget::slot_text_changed()
{
    if (!ui->searchEdit->text().isEmpty()) {
        ShowSearch(true);
    }
}

void ChatWidget::SlotApplyFriend(std::shared_ptr<AddFriendApply> apply)
{
    qDebug() << "receive apply friend slot, applyuid is " << apply->_from_uid << " name is "
        << apply->_name << " desc is " << apply->_desc;

   bool b_already = UserMgr::GetInstance()->AlreadyApply(apply->_from_uid);
   if(b_already){
        return;
   }

   UserMgr::GetInstance()->AddApplyList(std::make_shared<ApplyInfo>(apply));
    ui->side_contact_lb->ShowRedPoint(true);
    ui->conUserList->ShowRedPoint(true);
    ui->friendApplyPage->AddNewApply(apply);
}

void ChatWidget::slotAddAuthFriend(std::shared_ptr<AuthInfo> auth_info)
{
    qDebug() << "ChatWidget::slotAddAuthFriend receive slot_add_auth__friend uid is " << auth_info->_uid
            << " name is " << auth_info->_name << " nick is " << auth_info->_nick;

        //判断如果已经是好友则跳过
        auto bfriend = UserMgr::GetInstance()->CheckFriendById(auth_info->_uid);
        if(bfriend){
            return;
        }

        UserMgr::GetInstance()->AddFriend(auth_info);

        int randomValue = QRandomGenerator::global()->bounded(100); // 生成0到99之间的随机整数
        int str_i = randomValue % strs.size();
        int head_i = randomValue % heads.size();
        int name_i = randomValue % names.size();

        auto* chat_user_wid = new ChatUserWid();
        auto user_info = std::make_shared<UserInfo>(auth_info);
        chat_user_wid->SetInfo(user_info);
        QListWidgetItem* item = new QListWidgetItem;
        //qDebug()<<"chat_user_wid sizeHint is " << chat_user_wid->sizeHint();
        item->setSizeHint(chat_user_wid->sizeHint());
        ui->chatUserList->insertItem(0, item);
        ui->chatUserList->setItemWidget(item, chat_user_wid);
        _chat_items_added.insert(auth_info->_uid, item);
}

void ChatWidget::SlotAuthRsp(std::shared_ptr<AuthRsp> auth_rsp)
{
    qDebug() << "ChatWidget::SlotAuthRsp   receive slot_auth_rsp uid is " << auth_rsp->_uid
             << " name is " << auth_rsp->_name << " nick is " << auth_rsp->_nick;

    //判断如果已经是好友则跳过
    auto bfriend = UserMgr::GetInstance()->CheckFriendById(auth_rsp->_uid);
    if(bfriend){
        return;
    }

    UserMgr::GetInstance()->AddFriend(auth_rsp);
    int randomValue = QRandomGenerator::global()->bounded(100); // 生成0到99之间的随机整数
    int str_i = randomValue % strs.size();
    int head_i = randomValue % heads.size();
    int name_i = randomValue % names.size();

    auto* chat_user_wid = new ChatUserWid();
    auto user_info = std::make_shared<UserInfo>(auth_rsp);
    chat_user_wid->SetInfo(user_info);
    QListWidgetItem* item = new QListWidgetItem;
    //qDebug()<<"chat_user_wid sizeHint is " << chat_user_wid->sizeHint();
    item->setSizeHint(chat_user_wid->sizeHint());
    ui->chatUserList->insertItem(0, item);
    ui->chatUserList->setItemWidget(item, chat_user_wid);
    _chat_items_added.insert(auth_rsp->_uid, item);
}

void ChatWidget::SlotTextChatMsg(std::shared_ptr<TextChatMsg> msg)
{
    auto find_iter = _chat_items_added.find(msg->_from_uid);
    if(find_iter != _chat_items_added.end()){
        qDebug() << "set chat item msg, uid is " << msg->_from_uid;
        QWidget *widget = ui->chatUserList->itemWidget(find_iter.value());
        auto chat_wid = qobject_cast<ChatUserWid*>(widget);
        if(!chat_wid){
            return;
        }
        chat_wid->updateLastMsg(msg->_chat_msgs);
        //更新当前聊天页面记录
        UpdateChatMsg(msg->_chat_msgs);
        UserMgr::GetInstance()->AppendFriendChatMsg(msg->_from_uid,msg->_chat_msgs);
        return;
    }

    //如果没找到，则创建新的插入listwidget

    auto* chat_user_wid = new ChatUserWid();
    //查询好友信息
    auto fi_ptr = UserMgr::GetInstance()->GetFriendById(msg->_from_uid);
    chat_user_wid->SetInfo(fi_ptr);
    QListWidgetItem* item = new QListWidgetItem;
    //qDebug()<<"chat_user_wid sizeHint is " << chat_user_wid->sizeHint();
    item->setSizeHint(chat_user_wid->sizeHint());
    chat_user_wid->updateLastMsg(msg->_chat_msgs);
    UserMgr::GetInstance()->AppendFriendChatMsg(msg->_from_uid,msg->_chat_msgs);
    ui->chatUserList->insertItem(0, item);
    ui->chatUserList->setItemWidget(item, chat_user_wid);
    _chat_items_added.insert(msg->_from_uid, item);
}

void ChatWidget::UpdateChatMsg(std::vector<std::shared_ptr<TextChatData> > msgdata)
{
    for(auto & msg : msgdata){
        if(msg->_from_uid != _cur_chat_uid){
            break;
        }
        ui->chatPage->AppendChatMsg(msg);
    }
}
bool  ChatWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        handleGlobalMousePress(mouseEvent);
    }
    return QWidget::eventFilter(watched, event);
}

void ChatWidget::handleGlobalMousePress(QMouseEvent *event)
{
    // 实现点击位置的判断和处理逻辑
    // 先判断是否处于搜索模式，如果不处于搜索模式则直接返回
    if( _mode != ChatUIMode::SearchMode){
        return;
    }

    // 将鼠标点击位置转换为搜索列表坐标系中的位置
    QPoint posInSearchList = ui->searchList->mapFromGlobal(event->globalPos());
    // 判断点击位置是否在聊天列表的范围内
    if (!ui->searchList->rect().contains(posInSearchList)) {
        // 如果不在聊天列表内，清空输入框
        ui->searchEdit->clear();
        ShowSearch(false);
        ui->side_chat_lb->SetSelected(true);
    }
}

void ChatWidget::ClearLabelState(StateWidget *lb)
{
    for(auto & ele: _lb_list){
        if(ele == lb){
            continue;
        }

        ele->ClearState();
    }
}

void ChatWidget::AddLBGroup(StateWidget *lb)
{
     _lb_list.push_back(lb);
}


void ChatWidget::setTitleBar()
{
    ui->minimize_btn->SetState("normal","hover","press");
    connect(ui->minimize_btn,&QPushButton::clicked,this,[=](){
        showMinimized();
    });


    ui->maximize_btn->SetState("normal","hover","press");
    connect(ui->maximize_btn,&QPushButton::clicked,this,[=](){
        qDebug()<< _windowFlag;
        if (_windowFlag) {
            // 如果之前是最大化状态，恢复到正常大小
            showNormal();
            _windowFlag = false;
        } else{
            // 如果当前是最大化状态，显示最大化窗口
            showMaximized();
            _windowFlag = true;
        }

    });
    ui->close_btn->SetState("normal","hover","press");
    connect(ui->close_btn,&QPushButton::clicked,this,[=](){
        QTimer::singleShot(500, [this]()
        {
            QCoreApplication::quit();
        });

    });

    // 监听边框


    // 设置无边框
   // this->setWindowFlags(Qt::FramelessWindowHint | Qt::CustomizeWindowHint);
    this->setMaximumSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX);
    this->setMinimumSize(1050,900);
}

void ChatWidget::setSearchBar()
{
    //链接搜索框输入变化
    connect(ui->searchEdit, &QLineEdit::textChanged, this, &ChatWidget::slot_text_changed);
}
